package com.lenovo.smarttraffic.ui.fragment;


import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.bean.RechargeRecordInfo;
import com.lenovo.smarttraffic.database.dao.CarAccountDataBase;
import com.lenovo.smarttraffic.ui.adapter.RechargeRecordListAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class RechargeRecordFragment extends Fragment {

    private RechargeRecordInfo info;
    private List<RechargeRecordInfo> list;
    private Context context;
    private RechargeRecordListAdapter adapter;

    public RechargeRecordFragment() {
        // Required empty public constructor
    }

    //获取数据库数据
    private void getData() {
        //首先创建数据库，防止没有数据库使程序崩溃
        CarAccountDataBase carAccountDataBase = new CarAccountDataBase(getActivity(), "CarAccount.db", null, 1);
        carAccountDataBase.getWritableDatabase();
        //获取数据库数据
        list = new ArrayList<>();
        SQLiteDatabase db = carAccountDataBase.getWritableDatabase();
        Cursor cursor = db.query("CarAccount", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                //遍历Cursor对象，取出数据并打印
                info = new RechargeRecordInfo();
                info.setPlate(cursor.getString(cursor.getColumnIndex("plate")));
                info.setMoney(cursor.getInt(cursor.getColumnIndex("money")));
                info.setBalance(cursor.getInt(cursor.getColumnIndex("balance")));
                info.setPeople(cursor.getString(cursor.getColumnIndex("people")));
                info.setTime(cursor.getString(cursor.getColumnIndex("time")));
                list.add(info);
            } while (cursor.moveToNext());
        }
        cursor.close();
        //复制第一行数据，使第一行显示文字提示信息
        list.add(0, list.get(0));
    }

    //当Fragment和Activity建立联系的时候初始化数据
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        //获取数据库的数据
        getData();
        //配置ListView
        adapter = new RechargeRecordListAdapter(context, list);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_recharge_record, container, false);
        //设置ListView
        ListView listView = view.findViewById(R.id.recharge_record_list);
        listView.setAdapter(adapter);
        return view;
    }

}
